#include "recbox.h"
#include "ui_recbox.h"
#include"recboxitem.h"
#include<QJsonObject>
#include<QJsonValue>
RecBox::RecBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBox),
    row(1),col(4)


{
    ui->setupUi(this);

}

RecBox::~RecBox()
{
    delete ui;
}

void RecBox::initRecBoxUi(const QJsonArray &arr, int row)
{

        if(row==2)
        {
            this->row=row;
            this->col=8;
        }
        else
        {
            //隐藏一行
            ui->recListDown->hide();
        }
        imageList=arr;

        currentindex=0;
        count=imageList.size()/col;
        createRecItem();
}

void RecBox::createRecItem()
{
    //创建recBoxItem对象之前,先把里面的元素先清理掉
    QList<RecBoxItem*> ListitemsUp=ui->recListUp->findChildren<RecBoxItem*>();
    for(auto e:ListitemsUp)
    {
       ui->recListUpLayOut->removeWidget(e);
       delete e;
    }

    QList<RecBoxItem*> ListitemsDown=ui->recListDown->findChildren<RecBoxItem*>();
    for(auto e:ListitemsDown)
    {
       ui->recListDownLayOut->removeWidget(e);
       delete e;
    }

    //创建recBoxItem对象往recBox中添加
    for(int i=0;i<col;i++)
    {
        RecBoxItem* item=new RecBoxItem();
        //拿到object对象-->调用val拿到对应的text值
        QJsonObject obj=imageList[i+currentindex*col].toObject();

        QString path=obj.value("path").toString();
        QString text=obj.value("text").toString();
        item->setImage(path);
        item->setText(text);

        if(i>=col/2&&row==2)
        {
            ui->recListDownLayOut->addWidget(item);
        }
        else
        {
            ui->recListUpLayOut->addWidget(item);
        }

    }

}

void RecBox::on_btDown_clicked()
{
    //展示下一页
    currentindex++;
    if(currentindex>=count)
    {
        currentindex=0;
    }
    createRecItem();
}

void RecBox::on_btUp_clicked()
{
    //展示上一页
    currentindex--;
    if(currentindex<0)
    {
        currentindex=count-1;
    }
    createRecItem();
}
